package com.ruoyi.task;

import com.ruoyi.domain.UserHealthGoals;
import com.ruoyi.service.UserHealthGoalsService;
import com.ruoyi.service.UserDeviceDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class HealthGoalTask {

    @Autowired
    private UserHealthGoalsService userHealthGoalsService;

    @Autowired
    private UserDeviceDataService userDeviceDataService;

    /**
     * 定时任务：每隔 1 分钟检查并更新目标的实际值（steps 或 active_minutes）
     */
    @Scheduled(cron = "0 */1 * * * ?")  // 每分钟执行一次
    public void updateUserHealthGoals() {
        // 获取所有未完成的健康目标
        List<UserHealthGoals> goals = userHealthGoalsService.getAllActiveGoals();

        for (UserHealthGoals goal : goals) {
            // 获取用户的设备数据，依据目标类型（1: 步数，2: 运动时间）
            Integer actualValue = 0;
            if (goal.getName() == 1) {
                // 目标是运动步数，获取步数
                actualValue = userDeviceDataService.getTotalSteps(goal.getUserId(), goal.getDate());
            } else if (goal.getName() == 2) {
                // 目标是运动时间，获取运动时间
                actualValue = userDeviceDataService.getTotalActiveMinutes(goal.getUserId(), goal.getDate());
            }

            // 更新目标的实际值
            goal.setActualValue(actualValue);

            // 如果实际值超过目标值，更新状态为已完成
            if (actualValue >= goal.getTargetValue()) {
                goal.setStatus(1);  // 设置为已完成
            }

            // 保存更新后的目标
            userHealthGoalsService.updateHealthGoal(goal);
        }
    }
}
